<template>
  <div class="main-bg">
    <el-button type="primary" size="small" style="float: right;margin-top: 10px;" @click="addOrUpdateHandle()">发布新版本</el-button>

    <div class="container">
      <el-table :data="tableData" v-loading="loading" style="width: 100%">
        <el-table-column prop="appName" align="center" label="应用名称" min-width="60" />
        <el-table-column align="center" label="应用类型" min-width="60">
          <template v-slot="scope">
            {{ scope.row.appType == 1 ? 'Android' :  scope.row.appType == 2 ? 'ios' : 'PC' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="设备类型" min-width="60">
          <template v-slot="scope">
            {{ scope.row.deviceType == 1 ? 'APP' : scope.row.deviceType == 2 ? 'ipad' : 'PC' }}
          </template>
        </el-table-column>
        <el-table-column prop="appVersion" align="center" label="应用版本号" min-width="60" />
        <el-table-column align="center" label="是否强制更新" min-width="60">
          <template v-slot="scope">
            {{ scope.row.isForce == 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="appUrl" align="center" label="下载地址" show-overflow-tooltip/>
        <el-table-column prop="createTime" align="center" label="上传时间">
          <template v-slot="scope">
            {{ $utils.getCompleteDate(scope.row.createTime, 'yyyy-MM-dd HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="merchantCoding" header-align="left" align="left" label="操作" width="240">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="addOrUpdateHandle(scope.row.editionId)">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteHandle(scope.row.editionId)">删除</el-button>
            <el-button type="primary" size="small" @click="download(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagination_pos" :current-page="pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle" @current-change="pageCurrentChangeHandle"></el-pagination>
    </div>
    <el-dialog title="发布新版本" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" :rules="dataRule" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应用名称" prop="appName">
              <el-input type="text" v-model="dataForm.appName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用类型" prop="appType">
              <el-select v-model="dataForm.appType" placeholder="请选择" clearable class="w_100">
                <el-option label="Android" value="1" />
                <el-option label="iOS" value="2" />
                <el-option label="PC" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="dataForm.deviceType" placeholder="请选择" clearable class="w_100">
                <el-option label="APP" value="1" />
                <el-option label="Pad" value="2" />
                <el-option label="PC" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用版本号" prop="appVersion">
              <el-input type="text" v-model="dataForm.appVersion"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否强制更新" prop="isForce">
              <el-radio-group v-model="dataForm.isForce" class="w_100">
                <el-radio label="1">是</el-radio>
                <el-radio label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="更新内容">
              <el-input type="textarea" v-model="dataForm.updateLog" :autosize="{ minRows: 3 }" show-word-limit :maxlength="300" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传安装包"><br/>
              <el-upload
                action="https://trade.zhuanqianpa.cn/trade_master/oss/getEditionLogUrl"
                :on-success="handleAvatarSuccess"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="1"
                :on-exceed="handleExceed"
                :headers="headers"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitForm">确定</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getEditionListPage,getEditionById,deleteEdition,updateEdition,saveEdition } from  "@/api/system/systemVersion";
import debounce from 'lodash/debounce';
import axios from 'axios';

export default {
  name: "systemVersion",
  data() {
    return {
      dialogVisible: false,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      headers:{
        token:localStorage.getItem('token'),
        logType:1,
      },
      tableData: [],
      loading: true,
      dataForm: {
        editionId: '',
        appName: '',
        appType: '',
        deviceType: '',
        appVersion: '',
        isForce: '1',
        appUrl: '',
        upgradePoint: '',
        updateLog: '',
        remark: ''
      },
      fileList: [],
    }
  },
  computed: {
    dataRule () {
      return {
        appName: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
        appType: [{ required: true, message: '请选择应用类型', trigger: 'blur' }],
        deviceType: [{ required: true, message: '请选择设备类型', trigger: 'blur' }],
        appVersion: [{ required: true, message: '请输入应用版本号', trigger: 'blur' }],
        isForce: [{ required: true, message: '请选择', trigger: 'blur' }],
        appUrl: [{ required: true, message: '请选择安装包', trigger: 'blur' }],
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    download(row){
      window.open(
        'https://trade.zhuanqianpa.cn/trade_master/oss/downloadOss?downloadPath='+row.appUrl,
      );
    },
    // 获取分页数据
    getList() {
      let body = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        table: {}
      }
      getEditionListPage({ body }).then(res => {
        this.pageNum = res.body.currentPage;
        this.loading=false
        this.total = res.body.totalCount;
        this.tableData = res.body.list;
      }).catch(err => {
        throw new Error(err);
      })
    },
    // 获取详情
    getDetails(editionId) {
      let body = { editionId }
      getEditionById({ body }).then(res => {
        this.dataForm = {
          ...this.dataForm,
          ...res.body
        }
        this.dataForm.isForce = res.body.isForce == 1 ? '1' : '2';
      }).catch(err => {
        throw new Error(err);
      })
    },
    // 新增/编辑弹框
    addOrUpdateHandle(editionId) {
      if(editionId) {  //编辑
        this.dataForm.editionId = editionId;
        this.getDetails(editionId);
      }else {
        this.fileList=[]
        this.dataForm.appUrl=''
        for(let key in this.dataForm) {
          if(key != 'appUrl') {
            this.dataForm[key] = '';
          }
        }
      }
      this.dialogVisible = true;
    },
    // 删除
    deleteHandle(editionId) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let body = { editionId }
          deleteEdition({ body }).then(res => {
            if(res.code != 2000) {
              return this.$message.error(res.msg)
            }
            this.$message.success(res.msg);
            this.getList();
          }).catch(err => {
            throw new Error(err);
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {

    },
    beforeRemove(file, fileList) {

    },
    handleAvatarSuccess(res, file){
      this.dataForm.appUrl = res.body
    },
    downLoad(row){
      window.location.href = row.appUrl
    },
    //pageSize 改变时会触
    pageSizeChangeHandle(value) {
      this.pageNum = 1;
      this.pageSize = value;
      this.getList();
    },
    // pageNum 改变时会触发
    pageCurrentChangeHandle(value) {
      this.pageNum = value;
      this.getList();
    },
    // 提交店员信息
    submitForm: debounce(function () {
      this.$refs['formRef'].validate(async (valid) => {
        if(!valid) {
          return false
        }
        let body = { ...this.dataForm }
        if(this.dataForm.editionId){
          updateEdition({body}).then(res => {
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.dialogVisible = false;
                this.getList();
            })
          }else{
            saveEdition({body}).then(res => {
                this.$message({
                  message: res.msg,
                  type: 'success'
                });
                this.dialogVisible = false;
                this.getList();
            })
          }
      });
    }, 1000, { 'leading': true, 'trailing': false }),
  },
}
</script>

<style scoped>
  .pagination_pos {
    float: right;
    margin-top: 28px;
  }
  .w_100 {
    width: 100% !important;
  }
</style>
